﻿using NLog;
using Simple.Framework.Configuration;
using Simple.Framework.Schedule;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Simple.FileBackClient
{
	internal class BackupsDatabaseSchedule:ISchedule
	{
		List<string> commands;
		ILogger logger;
		public BackupsDatabaseSchedule(IClientConfiguration configuration,ILogger logger)
		{
			ScheduleInfo = new ScheduleInfo();
			Schedule schedule = configuration.Schedules[1];
			ScheduleInfo.Title = "数据库备份!";
			
			commands = configuration.BackupsDBCommands;
			this.logger = logger;
			TimeSpan now = DateTime.Now.TimeOfDay;
			if (schedule.BackupsTime.Ticks >= now.Ticks)
			{
				ScheduleInfo.BeforeStartWait = schedule.BackupsTime.Ticks - now.Ticks;
			}
			else
			{
				ScheduleInfo.BeforeStartWait = now.Ticks - schedule.BackupsTime.Ticks + TimeSpan.TicksPerDay;
			}
			ScheduleInfo.Period = schedule.Cycle* TimeSpan.TicksPerDay;
		}

		public ScheduleInfo ScheduleInfo { get; set; }

		public void Run()
		{
			logger.Info("开始备份");
			using (Process _proc = new Process())
			{
                foreach (var item in commands)
                {
					string Params = $"{item}_back_{DateTime.Now.ToString("yyyy_MM_dd_HH_m_s")}.sql";
					ProcessStartInfo _procStartInfo = new ProcessStartInfo($"D:\\vgm\\MySQL Server 8.0\\bin\\mysqldump.exe",Params);
					_proc.StartInfo = _procStartInfo;
					_procStartInfo.RedirectStandardInput = false;
					_procStartInfo.RedirectStandardOutput = true;
					_proc.Start();
					logger.Info("DataBase Backup Has Been Completed Successfully!");
					logger.Info(Params);
				}
			}
		}
	}
}
